// components/lyric/lyric.js 
let lyricHeight = 0; // 歌词高度
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShowLyric: {
      type: Boolean,
      value: false
    },
    lyric: String
  },
  observers: {
    lyric(lrc) {
      if (lrc === '暂无歌词') {
        this.setData({
          lyricList: [{
            lrc,
            time: 0
          }],
          nowLyricIndex: -1
        })
      } else {
        this._passLyric(lrc)

      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    lyricList: [],
    nowLyricIndex: 0, //当前选中歌词的下标
    scrollTop: 0,
  },
  /**
   * 生命周期
   */
  lifetimes: {
    ready() {
      /**
       * 计算当前rpx与px的单位的关系
       */
      //获取系统信息
      wx.getSystemInfo({
        success: function(res) {
          //获取比例1px 和1rpx的换算 默认歌词最小单位为64rpx,求出64rpx等于多少px
          lyricHeight = res.screenWidth / 750 * 64;
        },
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    toggleLyric() {
      this.triggerEvent("toggleLyric")
    },
    updataTime(currentTime) {
      let lyricList = this.data.lyricList;
      if (lyricList.length === 0) return false;
      //如果歌曲时长比歌词长
      if (currentTime > lyricList[lyricList.length - 1].time) {
        if (this.data.nowLyricIndex != -1) {
          this.setData({
            nowLyricIndex: -1,
            scrollTop: (lyricList.length - 1) * lyricHeight
          })
        }
      }
      for (let i = 0; i < lyricList.length; i++) {
        if (currentTime <= lyricList[i].time) {
          this.setData({
            nowLyricIndex: i - 1,
            scrollTop: (i - 1) * lyricHeight
          })
          break;
        }
      }
    },
    _passLyric(lrc) {
      let line = lrc.split("\n");
      let _lyricList = [];
      line.forEach(elem => {
        let time = elem.match(/\[(\d{2,}):(\d{2})(?:\.(\d{2,3}))?]/g)
        if (time != null) {
          let lrc = elem.split(time)[1];
          let timeReg = time[0].match(/(\d{2,}):(\d{2})(?:\.(\d{2,3}))?/)
          let time2Seconds = parseInt(timeReg[1]) * 60 + parseInt(timeReg[2]) + parseInt(timeReg[3]) / 1000;
          _lyricList.push({
            time: time2Seconds,
            lrc: lrc
          })
        }
      })
      this.setData({
        lyricList: _lyricList
      })
      // console.log(_lrcList)
    }
  }
})